package com.example.detectivedemo.ui;

import com.example.detectivedemo.application.AppService;
import com.example.detectivedemo.domain.product.Product;
import com.example.detectivedemo.utils.LogUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.layout.DirectionLayout;
import ohos.agp.layout.ListContainer;
import ohos.agp.layout.LinearLayout;
import ohos.agp.layout.LayoutAlignment;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 产品展示界面切片
 * 负责显示产品列表和产品详情
 */
public class ProductAbilitySlice extends AbilitySlice {
    
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00204, "ProductAbilitySlice");
    
    private AppService appService;
    private List<Product> productList;
    
    // UI组件
    private DirectionLayout rootLayout;
    private Text titleText;
    private Text statusText;
    private ListContainer productListContainer;
    private Button loadDataButton;
    private Button refreshButton;
    
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        
        // 初始化应用服务
        appService = AppService.getInstance();
        
        // 创建UI界面
        createUI();
        
        // 初始化模拟数据
        appService.initializeMockData();
        
        // 加载产品数据
        loadProductData();
        
        HiLog.i(LABEL, "ProductAbilitySlice onStart");
    }
    
    @Override
    public void onActive() {
        super.onActive();
        HiLog.i(LABEL, "ProductAbilitySlice onActive");
    }
    
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        HiLog.i(LABEL, "ProductAbilitySlice onForeground");
    }
    
    // 创建UI界面
    private void createUI() {
        // 创建根布局
        rootLayout = new DirectionLayout(this);
        rootLayout.setWidth(DirectionLayout.LayoutConfig.MATCH_PARENT);
        rootLayout.setHeight(DirectionLayout.LayoutConfig.MATCH_PARENT);
        rootLayout.setOrientation(Component.VERTICAL);
        rootLayout.setAlignment(LayoutAlignment.TOP);
        rootLayout.setBackgroundColor(new Color(0x000000)); // 黑色背景
        
        // 创建标题文本
        titleText = new Text(this);
        titleText.setText("产品列表展示");
        titleText.setTextSize(40);
        titleText.setTextColor(new Color(0xFFFFFF)); // 白色文字
        titleText.setTextAlignment(TextAlignment.CENTER);
        titleText.setMarginBottom(30);
        titleText.setPadding(20, 20, 20, 20);
        rootLayout.addComponent(titleText);
        
        // 创建状态文本
        statusText = new Text(this);
        statusText.setText("点击下方按钮加载产品数据");
        statusText.setTextSize(20);
        statusText.setTextColor(new Color(0x00FF00)); // 绿色文字
        statusText.setTextAlignment(TextAlignment.CENTER);
        statusText.setMarginBottom(20);
        statusText.setPadding(20, 10, 20, 10);
        rootLayout.addComponent(statusText);
        
        // 创建按钮布局
        DirectionLayout buttonLayout = new DirectionLayout(this);
        buttonLayout.setWidth(DirectionLayout.LayoutConfig.MATCH_PARENT);
        buttonLayout.setHeight(DirectionLayout.LayoutConfig.WRAP_CONTENT);
        buttonLayout.setOrientation(Component.HORIZONTAL);
        buttonLayout.setAlignment(LayoutAlignment.CENTER);
        buttonLayout.setMarginBottom(20);
        
        // 创建加载数据按钮
        loadDataButton = new Button(this);
        loadDataButton.setText("加载数据");
        loadDataButton.setWidth(200);
        loadDataButton.setHeight(80);
        loadDataButton.setTextSize(25);
        loadDataButton.setTextColor(new Color(0x000000));
        loadDataButton.setBackgroundColor(new Color(0x00FF00)); // 绿色
        loadDataButton.setMarginRight(20);
        loadDataButton.setClickedListener(component -> loadProductData());
        buttonLayout.addComponent(loadDataButton);
        
        // 创建刷新按钮
        refreshButton = new Button(this);
        refreshButton.setText("刷新数据");
        refreshButton.setWidth(200);
        refreshButton.setHeight(80);
        refreshButton.setTextSize(25);
        refreshButton.setTextColor(new Color(0x000000));
        refreshButton.setBackgroundColor(new Color(0x0000FF)); // 蓝色
        refreshButton.setClickedListener(component -> refreshProductData());
        buttonLayout.addComponent(refreshButton);
        
        rootLayout.addComponent(buttonLayout);
        
        // 创建产品列表容器
        productListContainer = new ListContainer(this);
        productListContainer.setWidth(ListContainer.LayoutConfig.MATCH_PARENT);
        productListContainer.setHeight(ListContainer.LayoutConfig.MATCH_PARENT);
        rootLayout.addComponent(productListContainer);
        
        // 设置根布局为内容
        super.setUIContent(rootLayout);
    }
    
    // 加载产品数据
    private void loadProductData() {
        statusText.setText("正在加载产品数据...");
        statusText.setTextColor(new Color(0xFFFF00)); // 黄色
        
        try {
            // 从服务层获取所有产品
            productList = appService.getAllProducts();
            
            if (productList.isEmpty()) {
                statusText.setText("没有产品数据");
                statusText.setTextColor(new Color(0xFFFFFF)); // 白色
            } else {
                statusText.setText("共加载到 " + productList.size() + " 个产品");
                statusText.setTextColor(new Color(0x00FF00)); // 绿色
                
                // 创建并设置产品适配器
                ProductAdapter adapter = new ProductAdapter(productList);
                productListContainer.setItemProvider(adapter);
                
                // 设置列表项点击事件
                productListContainer.setItemClickedListener((listContainer, component, i, l) -> {
                    showProductDetails(productList.get(i));
                });
            }
            
            HiLog.i(LABEL, "Loaded " + productList.size() + " products");
        } catch (Exception e) {
            statusText.setText("加载数据失败：" + e.getMessage());
            statusText.setTextColor(new Color(0xFF0000)); // 红色
            HiLog.e(LABEL, "Failed to load products: " + e.getMessage());
        }
    }
    
    // 刷新产品数据
    private void refreshProductData() {
        statusText.setText("正在刷新数据...");
        statusText.setTextColor(new Color(0xFFFF00)); // 黄色
        
        // 重新初始化模拟数据
        appService.initializeMockData();
        
        // 重新加载数据
        loadProductData();
    }
    
    // 显示产品详情
    private void showProductDetails(Product product) {
        // 创建产品详情对话框
        DirectionLayout dialogLayout = new DirectionLayout(this);
        dialogLayout.setWidth(600);
        dialogLayout.setHeight(DirectionLayout.LayoutConfig.WRAP_CONTENT);
        dialogLayout.setOrientation(Component.VERTICAL);
        dialogLayout.setAlignment(LayoutAlignment.CENTER);
        dialogLayout.setBackgroundColor(new Color(0x222222));
        dialogLayout.setPadding(30, 30, 30, 30);
        
        // 创建产品名称
        Text nameText = new Text(this);
        nameText.setText(product.getName());
        nameText.setTextSize(30);
        nameText.setTextColor(new Color(0x00FF00)); // 绿色
        nameText.setTextAlignment(TextAlignment.CENTER);
        nameText.setMarginBottom(20);
        dialogLayout.addComponent(nameText);
        
        // 创建产品ID
        Text idText = new Text(this);
        idText.setText("ID: " + product.getId());
        idText.setTextSize(15);
        idText.setTextColor(new Color(0xAAAAAA)); // 灰色
        idText.setMarginBottom(10);
        dialogLayout.addComponent(idText);
        
        // 创建产品分类
        Text categoryText = new Text(this);
        categoryText.setText("分类: " + product.getCategory());
        categoryText.setTextSize(20);
        categoryText.setTextColor(new Color(0xFFFFFF)); // 白色
        categoryText.setMarginBottom(10);
        dialogLayout.addComponent(categoryText);
        
        // 创建产品价格
        Text priceText = new Text(this);
        priceText.setText("价格: ¥" + product.getPrice());
        priceText.setTextSize(25);
        priceText.setTextColor(new Color(0xFFFF00)); // 黄色
        priceText.setMarginBottom(10);
        dialogLayout.addComponent(priceText);
        
        // 创建产品库存
        Text stockText = new Text(this);
        stockText.setText("库存: " + product.getStock() + " 件");
        stockText.setTextSize(20);
        stockText.setTextColor(new Color(0xFFFFFF)); // 白色
        stockText.setMarginBottom(10);
        dialogLayout.addComponent(stockText);
        
        // 创建产品描述
        Text descriptionText = new Text(this);
        descriptionText.setText("描述: " + product.getDescription());
        descriptionText.setTextSize(18);
        descriptionText.setTextColor(new Color(0xCCCCCC)); // 浅灰色
        descriptionText.setMarginBottom(20);
        descriptionText.setMultipleLine(true);
        dialogLayout.addComponent(descriptionText);
        
        // 创建关闭按钮
        Button closeButton = new Button(this);
        closeButton.setText("关闭");
        closeButton.setWidth(200);
        closeButton.setHeight(60);
        closeButton.setTextSize(20);
        closeButton.setTextColor(new Color(0x000000));
        closeButton.setBackgroundColor(new Color(0x00FF00)); // 绿色
        closeButton.setClickedListener(component -> {
            // 关闭对话框
            if (getComponentParent(dialogLayout) instanceof CustomDialog) {
                ((CustomDialog) getComponentParent(dialogLayout)).destroy();
            }
        });
        dialogLayout.addComponent(closeButton);
        
        // 创建并显示对话框
        CustomDialog dialog = new CustomDialog(this);
        dialog.setContentCustomComponent(dialogLayout);
        dialog.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        dialog.show();
    }
    
    // 产品列表适配器
    private class ProductAdapter extends BaseItemProvider {
        
        private final List<Product> products;
        
        public ProductAdapter(List<Product> products) {
            this.products = products;
        }
        
        @Override
        public int getCount() {
            return products.size();
        }
        
        @Override
        public Object getItem(int position) {
            return products.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            Product product = products.get(position);
            
            // 创建产品项布局
            DirectionLayout itemLayout = new DirectionLayout(componentContainer.getContext());
            itemLayout.setWidth(DirectionLayout.LayoutConfig.MATCH_PARENT);
            itemLayout.setHeight(200);
            itemLayout.setOrientation(Component.VERTICAL);
            itemLayout.setAlignment(LayoutAlignment.CENTER);
            itemLayout.setBackgroundColor(new Color(0x113333));
            itemLayout.setPadding(20, 20, 20, 20);
            itemLayout.setMarginTop(10);
            itemLayout.setMarginBottom(10);
            itemLayout.setMarginLeft(20);
            itemLayout.setMarginRight(20);
            
            // 创建产品名称
            Text nameText = new Text(componentContainer.getContext());
            nameText.setText(product.getName());
            nameText.setTextSize(25);
            nameText.setTextColor(new Color(0x00FF00)); // 绿色
            nameText.setTextAlignment(TextAlignment.CENTER);
            nameText.setMarginBottom(10);
            itemLayout.addComponent(nameText);
            
            // 创建产品分类和价格
            Text categoryPriceText = new Text(componentContainer.getContext());
            categoryPriceText.setText("分类: " + product.getCategory() + " | 价格: ¥" + product.getPrice());
            categoryPriceText.setTextSize(18);
            categoryPriceText.setTextColor(new Color(0xFFFF00)); // 黄色
            categoryPriceText.setTextAlignment(TextAlignment.CENTER);
            categoryPriceText.setMarginBottom(10);
            itemLayout.addComponent(categoryPriceText);
            
            // 创建产品库存
            Text stockText = new Text(componentContainer.getContext());
            stockText.setText("库存: " + product.getStock() + " 件");
            stockText.setTextSize(15);
            stockText.setTextColor(new Color(0xAAAAAA)); // 灰色
            stockText.setTextAlignment(TextAlignment.CENTER);
            itemLayout.addComponent(stockText);
            
            return itemLayout;
        }
    }
}